package com.vehiclemanagement.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vehiclemanagement.common.result.Result;
import com.vehiclemanagement.dto.UserDTO;
import com.vehiclemanagement.entity.User;
import com.vehiclemanagement.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/user")
@Slf4j
@PreAuthorize("hasRole('ADMIN')")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 分页查询用户列表
     */
    @GetMapping("/list")
    public Result<IPage<User>> list(
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(value = "searchTerm", required = false) String searchTerm,
            @RequestParam(value = "role", required = false) Integer role,
            @RequestParam(value = "status", required = false) Integer status) {
        
        log.info("查询用户列表: current={}, size={}, searchTerm={}, role={}, status={}", 
                current, size, searchTerm, role, status);
        
        try {
            IPage<User> page = userService.pageUsers(current, size, searchTerm, role, status);
            return Result.success(page);
        } catch (Exception e) {
            log.error("查询用户列表失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取用户详情
     */
    @GetMapping("/{id}")
    public Result<User> getById(@PathVariable Long id) {
        log.info("获取用户详情: id={}", id);
        
        try {
            User user = userService.getUserById(id);
            if (user == null) {
                return Result.error("用户不存在");
            }
            return Result.success(user);
        } catch (Exception e) {
            log.error("获取用户详情失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加用户
     */
    @PostMapping
    public Result<Boolean> add(@Valid @RequestBody UserDTO userDTO) {
        log.info("添加用户: {}", userDTO.getUsername());
        
        try {
            boolean success = userService.register(userDTO);
            return success ? Result.success("添加用户成功", true) : Result.error("添加用户失败");
        } catch (Exception e) {
            log.error("添加用户失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新用户
     */
    @PutMapping
    public Result<Boolean> update(@Valid @RequestBody UserDTO userDTO) {
        log.info("更新用户: id={}", userDTO.getId());
        
        if (userDTO.getId() == null) {
            return Result.validateFailed("用户ID不能为空");
        }
        
        try {
            boolean success = userService.updateUserInfo(userDTO);
            return success ? Result.success("更新用户成功", true) : Result.error("更新用户失败");
        } catch (Exception e) {
            log.error("更新用户失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        log.info("删除用户: id={}", id);
        
        try {
            boolean success = userService.deleteUser(id);
            return success ? Result.success("删除用户成功", true) : Result.error("删除用户失败");
        } catch (Exception e) {
            log.error("删除用户失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 修改用户状态
     */
    @PutMapping("/{id}/status/{status}")
    public Result<Boolean> updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        log.info("修改用户状态: id={}, status={}", id, status);
        
        try {
            boolean success = userService.updateUserStatus(id, status);
            return success ? Result.success("修改状态成功", true) : Result.error("修改状态失败");
        } catch (Exception e) {
            log.error("修改用户状态失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
} 